import java.util.*;


public class Commander implements JSCommander {

	private static Map<String, JSCommand> commandMap;

	static {
		
		commandMap = new HashMap<String, JSCommand>();
		
		// Load all JSCommand objects to memory
		commandMap.put("mkdir", new MakeDir());
		commandMap.put("cd", new ChangeDir());
		commandMap.put("ls", new ListFiles());
		commandMap.put("pwd", new PresentWorkDir());
		commandMap.put("mv", new Move());
		commandMap.put("cp", new Copy());
		commandMap.put("cat", new Cat());
		commandMap.put("get", new Get());
		commandMap.put("echo", new Echo());
	
	}
	
	private static JSCommand getCommand(String commandName) {
		return commandMap.get(commandName);
	}

	public String runCommand(String[] commandArray, JShell shell) {
		
		String commandNotFoundError = "%s: command not found";
		String result = new String();
		
		// If commandArray is empty, return the empty string
		// Else, handle the command, i.e. the first string in commandArray
		int commandLength = commandArray.length;
		if (commandLength != 0) {
			
			// Fetch the JSCommand object corresponding to the request
			String commandName = commandArray[0];
			JSCommand command = getCommand(commandName);
			
			// Check if command exists and set result accordingly
			if (command == null) {
				result = String.format(commandNotFoundError, commandName);
			} else {
				result = command.runCommand(commandArray, shell);
			}
		}
		
		return result;
	}
	
	public static void main(String[] args) {
		
		// Test
		JSCommander jsc = new Commander();
		String[] commandArray1 = {"get", "arg1", "arg2"}; // Valid + arguments
		String[] commandArray2 = {"not-a-command", "arg1", "arg2"}; // Invalid + arguments
		String[] commandArray3 = {"cat"}; // Valid, no arguments
		String[] commandArray4 = {"not-a-command"}; // Invalid, no arguments
		System.out.println(jsc.runCommand(commandArray1, null));
		System.out.println(jsc.runCommand(commandArray2, null));
		System.out.println(jsc.runCommand(commandArray3, null));
		System.out.println(jsc.runCommand(commandArray4, null));
		System.out.println("End of test");

	}

}
